package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.domain.Weibo;
import cn.itcast.domain.WeiboComm;
import cn.itcast.service.UserService;
import cn.itcast.service.WeiboService;
import cn.itcast.utils.CommPage;
import cn.itcast.utils.FaceFormat;
import cn.itcast.utils.PageBean;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Date :17:49 2021/6/14
 * @Author :xuhe
 */
@Controller
public class WeiboController {

    @Autowired
    private WeiboService weiboService;

    @Autowired
    private UserService userService;

     private User user = new User();
    /**
     * 发布微博
     * 将前段传来的微博文本保存在weibo对象中
     * 从session中获取登陆对象
     * 判断用户输入的图片是否为空，为空则将weibo对象中的图片属性设置为null
     * 保存用户上传的图片到upload/pic中，并在图片开头加上用户id
     * 设置weibo对象中方的图片地址
     * 保存微博信息
     * 将用户微博数+1
     * 保存更改后的用户信息
     */
    @RequestMapping("/publishWeibo")
//    @RequestParam("pic") MultipartFile pic,
    public ModelAndView publishWeibo(String body, MultipartFile pic, HttpSession session, HttpServletRequest req){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("forward:home_index");
       // mav.setViewName("home");
        Weibo weibo = new Weibo();
        weibo.setBody(body);

        user = (User)session.getAttribute("user");
        if (user==null){
            mav.addObject("msg","请先登录");
            return mav;
        }
        if(!(pic.isEmpty())){	//如果文件存在，isEmpty文件为空
            //保存文件目录,weizhi
            String path = req.getSession().getServletContext().getRealPath("/upload/");
            //"upload/pic/"+user.getUserid()+pic.getOriginalFilename();
            //String path = req.getContextPath()+"/upload/pic/"+user.getUserid()+pic.getOriginalFilename();
            File newFile = new File(path);
            //判断文件目录存在不存在，如果不存在就创建目录
            if (!newFile.exists()){
                newFile.mkdirs();
            }
            String filename=user.getUserid()+pic.getOriginalFilename();
//            //判断文件目录存在不存在，如果不存在就创建目录
//            if(!(newFile.getParentFile().exists())){
//                newFile.getParentFile().mkdirs();
//            }
            try {
                pic.transferTo(new File(path,filename)); //转存文件
                weibo.setImage("upload/"+filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            //没有带图片
            weibo.setImage("null");
        }
        try {
            //保存微博信息
            weibo.setUser(user);
            weiboService.publishWeibo(weibo);	//保存微博信息
            user.setBlogNumber(user.getBlogNumber()+1);		//将用户的微博数+1
            userService.updateUser(user);		//保存更改后的用户信息
            session.setAttribute("user", user);
            System.out.println("发送成功");
            mav.addObject("msg", "发布成功！");

            //mav.setViewName("home");
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("msg", e.getMessage());
            //mav.setViewName("home");
        }
        return mav;
    }

    @RequestMapping("/home_index")
    public ModelAndView showWeibo(HttpSession session){
        System.out.println("发了");
        ModelAndView mav=new ModelAndView();
        mav.setViewName("home");
        User user = (User)session.getAttribute("user");
        List<Weibo> weiboList= weiboService.findAllWeibo();
        //====================================
        System.out.println(weiboList.get(0).getBody());
        //weiboList = FaceFormat.formt(weiboList);
        for (int i=0;i<weiboList.size();i++){
            //获取发微博的user
            System.out.println(weiboList.get(i).getBody());
            User wb_user=userService.findUserByid(weiboList.get(i).getUserid());
            //将weibo_user信息组装到weibo类中
            weiboList.get(i).setUser(wb_user);
        }

        mav.addObject("weiboList",weiboList);
        return mav;
    }

    @RequestMapping("/myWeibo")
    public ModelAndView myWeibo(HttpSession session){
        //System.out.println("发了");
        ModelAndView mav=new ModelAndView();
        mav.setViewName("home");
        User user = (User)session.getAttribute("user");
        List<Weibo> weiboList= weiboService.findWeiboByUserid(user.getUserid());
        //============================================
        //System.out.println(weiboList.get(0).getBody());
        //weiboList = FaceFormat.formt(weiboList);
        for (int i=0;i<weiboList.size();i++){
            //获取发微博的user
            System.out.println(weiboList.get(i).getBody());
            User wb_user=userService.findUserByid(weiboList.get(i).getUserid());
            //将weibo_user信息组装到weibo类中
            weiboList.get(i).setUser(wb_user);
        }

        mav.addObject("weiboList",weiboList);
        return mav;
    }

    /**
     * 微博评论
     * url="pubComment?weiboId="+id+"comment="+msg.value;
     * weiboId : 微博编号
     * comment : 评论内容
     */
    @RequestMapping("/test")
    public ModelAndView pubCommentTest(String weiboId, String comment, HttpSession session, HttpServletResponse resp){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("home");
        long id = Long.parseLong(weiboId);		//获取微博id
        User user = (User)session.getAttribute("user");	//评论人

        WeiboComm comm = new WeiboComm();
        //组装数据源
        comm.setWeiboid(id);	//微博id
        comm.setCommentid(user.getUserid()); 	//评论人id
        comm.setCommentBody(comment);
//        comm.setCommentState(1); 	//评论状态 1代表正常 2代表被删除 3代表被举报

        try {
            resp.setContentType("text/html");
            PrintWriter pw = resp.getWriter();
            int commNum = weiboService.weiboComment(comm);
            pw.print("评论("+commNum+")");

            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mav;
    }




    @RequestMapping("/showCom")
    public ModelAndView showComm(String weiboid,HttpSession session){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("forward:home");
        //获取微博id
        long id = Long.parseLong(weiboid);
        List<WeiboComm> commList= weiboService.finCommByWid(id);
        for (int i=0;i<commList.size();i++){
            //获取发微博的user
            System.out.println(commList.get(i).getCommentBody());
            User wb_user=userService.findUserByid(commList.get(i).getCommentid());
            //将weibo_user信息组装到weibo类中
            commList.get(i).setCommUser(wb_user);
        }
        mav.addObject("commList",commList);
        return mav;
    }


    @RequestMapping("/pubComment")
    public String pubComment(String weiboId, String comment, HttpSession session, HttpServletResponse resp){
        long id = Long.parseLong(weiboId);		//获取微博id
        User user = (User)session.getAttribute("user");	//评论人
        WeiboComm comm = new WeiboComm();
        //组装数据源
        comm.setWeiboid(id);	//微博id
        comm.setCommentid(user.getUserid()); 	//评论人id
        comm.setCommentBody(comment);
        try {
            resp.setContentType("text/html");
            PrintWriter pw = resp.getWriter();
            int commNum = weiboService.weiboComment(comm);
            pw.print("评论("+commNum+")");
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取评论
     * @param weiboId
     * @param p
     * @param fy
     * @param session
     * @param resp
     * @return
     */
    @RequestMapping(value= "/getComm")
    public String getComm(String weiboId,String p,String fy,HttpSession session,HttpServletResponse resp){


       // PageBean page = new PageBean();
        CommPage commPage = new CommPage();
        long wId = Long.parseLong(weiboId);
        int page = Integer.parseInt(p);
        int zt = Integer.parseInt(fy);
        commPage.setPage(page);
        commPage.setMinPage(page*5-4);
        commPage.setMaxPage(page*5);
        if(zt == 1){
            //上一页
            commPage.setPage(page-1);
            commPage.setMinPage((page-1)*5-4);
            commPage.setMaxPage((page-1)*5);
        }else if(zt == 2){
            //下一页
            commPage.setPage(page+1);
            commPage.setMinPage((page+1)*5-4);
            commPage.setMaxPage((page+1)*5);
        }

        List<WeiboComm> comm = null;
        JSONArray json = null;
        try {
            int cNum = weiboService.findCommNum(wId);
            commPage.setTotalPage(cNum/5+1);

            comm = weiboService.finCommByWid(wId);
           // comm = FaceFormat.commFormt(comm);

            json = JSONArray.fromObject(comm);
            json.add(commPage);
            PrintWriter pw = resp.getWriter();
            resp.setContentType("application/json");
            pw.print(json.toString());
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/search")
    public ModelAndView search(String key,HttpSession session){
        System.out.println("已查找");
        ModelAndView mav=new ModelAndView();
        User user=(User) session.getAttribute("user");
        mav.setViewName("home");
        List<Weibo> weiboList= weiboService.search(key);
        for (int i=0;i<weiboList.size();i++){
            //获取发微博的user
            System.out.println(weiboList.get(i).getBody());
            User wb_user=userService.findUserByid(weiboList.get(i).getUserid());
            //将weibo_user信息组装到weibo类中
            weiboList.get(i).setUser(wb_user);
        }
        mav.addObject("weiboList",weiboList);
        return mav;
    }


    @RequestMapping("/exit")
    public String exit(HttpSession session){
        session.removeAttribute("user");
        return "../../index";
    }


}
